package com.kordar.api.handler;

import com.kordar.api.exception.ErrorType;
import com.kordar.api.exception.ServiceException;
import com.kordar.api.util.Response;
import com.kordar.api.util.ResponseUtil;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class ServiceExceptionHandler {

    /**
     * @param se 业务异常
     * @return
     * @ExceptionHandler相当于controller的@RequestMapping 如果抛出的的是ServiceException，则调用该方法
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public Response<Object> handle(ServiceException se) {
        return ResponseUtil.error(se.getCode(), se.getMessage());
    }


    @ExceptionHandler({BindException.class})
    @ResponseBody
    @CrossOrigin
    public Response<Object> validationExceptionHandler(BindException e) {
        if (!CollectionUtils.isEmpty(e.getBindingResult().getAllErrors())) {
            return ResponseUtil.error(ErrorType.VALIDATED_ERROR.getCode(), (e.getBindingResult().getAllErrors().get(0)).getDefaultMessage());
        } else {
            return ResponseUtil.error(ErrorType.VALIDATED_ERROR.getCode(), e.getMessage());
        }
    }
}
